package com.aw.baselib.util.update

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import com.aw.baselib.R
import com.aw.baselib.base.AwBaseApplication
import com.aw.baselib.base.AwViewDialog
import com.aw.baselib.interfaces.IPermissionListener
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwRxPermissionUtil
import com.aw.baselib.util.AwToastUtil
import com.aw.baselib.util.update.AwFileDownloadUtil.Companion.get
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.io.File

/**
 * Created by hzw
 */
class AwUpdateUtil(private var mActivity: Activity) {

    private val instance: AwUpdateUtil? = null
    protected var mDialog: AwViewDialog? = null
    protected var m4gDialog: AwViewDialog? = null
    protected var mDownloadDialog: AwViewDialog? = null
    fun getInstance(activity: Activity): AwUpdateUtil? {
        if (instance == null) {
            return AwUpdateUtil(activity)
        }
        showDownloadDialog()
        return instance
    }

    init {
        showDownloadDialog()
    }

    fun handleUpdate(updateBean: UpdateBean, iUpdateCancelInterface: IUpdateCancelInterface) {
        // 需要版本更新 展示弹框
        val textContent = """
               ${
            AwBaseApplication.instance?.getString(R.string.update_version)
        }${updateBean.appVersion}
               
               ${AwBaseApplication.instance?.getString(R.string.update_content)}
               ${updateBean.description}
               """.trimIndent()
        mDialog!!.showUpdateDialog(textContent, !updateBean.isForceUpdate, View.OnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val hasInstallPermission: Boolean =
                    mActivity.getPackageManager().canRequestPackageInstalls()
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity()
                    return@OnClickListener
                }
            }
            if (!updateBean.isForceUpdate) {
                mDialog!!.dismiss()
            }
            AwRxPermissionUtil.instance?.checkPermissions(
                mActivity,
                AwRxPermissionUtil.storagePermissions,
                object : IPermissionListener {
                    override fun granted() {
                        if (AwBaseApplication.netWatchdog?.hasNet(mActivity) == true) {
                            if (AwBaseApplication.netWatchdog?.is4GConnected(mActivity)!!) {
                                m4gDialog!!.showCommonDialog(
                                    mActivity.getString(R.string.update_hint_is_not_wifi),
                                    AwBaseApplication.instance?.getString(R.string.common_cancel),
                                    AwBaseApplication.instance?.getString(R.string.common_confirm),
                                    false,
                                    true,
                                    true,
                                    { v1: View? ->
                                        m4gDialog!!.dismiss()
                                        if (updateBean.isForceUpdate) {
                                            mActivity.finish()
                                        }
                                    }) { v12: View? ->
                                    m4gDialog!!.dismiss()
                                    updateBean.appurl?.let { it1 ->
                                        downloadFile(
                                            mActivity,
                                            it1,
                                            iUpdateCancelInterface
                                        )
                                    }
                                }
                            } else {
                                updateBean.appurl?.let { it1 ->
                                    downloadFile(
                                        mActivity,
                                        it1,
                                        iUpdateCancelInterface
                                    )
                                }
                            }
                        }
                    }

                    override fun shouldShowRequestPermissionRationale() {
                        AwToastUtil.showShort(
                            AwBaseApplication.instance,
                            mActivity.getString(R.string.update_hint_permission_1)
                        )
                        iUpdateCancelInterface.cancelUpdate()
                        //                                mActivity.finish();
                    }

                    override fun needToSetting() {
                        AwToastUtil.showShort(
                            AwBaseApplication.instance,
                            mActivity.getString(R.string.update_hint_permission_1)
                        )
                        iUpdateCancelInterface.cancelUpdate()
                        //                                AwSystemIntentUtil.toSelfSetting(mActivity);
                    }
                })
        }) {
            mDialog!!.dismiss()
            iUpdateCancelInterface.cancelUpdate()
        }
    }


    private fun showDownloadDialog() {
        mDialog = AwViewDialog(mActivity)
        m4gDialog = AwViewDialog(mActivity)
        mDownloadDialog = AwViewDialog(mActivity)
    }

    private fun downloadFile(
        activity: Activity,
        url: String,
        iUpdateCancelInterface: IUpdateCancelInterface
    ) {
        if (AwDataUtil.isEmpty(url)) {
            AwToastUtil.showShort(
                activity,
                AwBaseApplication.instance?.getString(R.string.update_download_url_empty)
            )
            mDownloadDialog!!.dismiss()
            iUpdateCancelInterface.cancelUpdate()
            return
        }
        mDownloadDialog!!.showDownloadDialog()
        val pb_loading =
            mDownloadDialog!!.dialog?.findViewById<View>(R.id.pb_loading) as ProgressBar
        val btn_cancel =
            mDownloadDialog!!.dialog?.findViewById<View>(R.id.btn_cancel) as TextView
        val tv_progress =
            mDownloadDialog!!.dialog?.findViewById<View>(R.id.tv_progress) as TextView
        pb_loading.max = 100
        btn_cancel.setOnClickListener {
            get()!!.cancel(activity, url)
            mDownloadDialog!!.dismiss()
            iUpdateCancelInterface.cancelUpdate()
        }
        get()!!.downApk(activity, url, object : AwFileDownloadUtil.OnDownloadListener {
            override fun onDownloadSuccess(path: String?) {
                Observable.just<String?>(path).observeOn(AndroidSchedulers.mainThread())
                    .subscribe { s ->
                        Toast.makeText(
                            activity,
                            AwBaseApplication.instance?.getString(R.string.download_success),
                            Toast.LENGTH_SHORT
                        ).show()
                        mDownloadDialog!!.dismiss()
                        openAPKFile(mActivity, s)
                    }
            }

            override fun onDownloading(progress: Int) {
                Observable.just(progress).observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        pb_loading.progress = progress
                        tv_progress.text = "$progress%"
                    }
            }

            override fun onDownloadFailed(path: String?) {
                Observable.just(0).observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        Toast.makeText(
                            activity,
                            AwBaseApplication.instance?.getString(R.string.download_success),
                            Toast.LENGTH_SHORT
                        ).show()
                        get()!!
                            .cancel(activity, url)
                        mDownloadDialog!!.dismiss()
                        iUpdateCancelInterface.cancelUpdate()
                    }
            }

            override fun onDownloadIngRejectRepeat() {}
        })
    }

    /**
     * 打开安装包
     *
     * @param mContext
     * @param fileUri
     */
    fun openAPKFile(mContext: Activity, fileUri: String?) {
        // 核心是下面几句代码
        if (null != fileUri) {
            try {
                val intent = Intent(Intent.ACTION_VIEW)
                val apkFile = File(fileUri)
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    val contentUri = FileProvider.getUriForFile(
                        mContext,
                        mContext.packageName + ".base.fileProvider",
                        apkFile
                    )
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        val hasInstallPermission =
                            mContext.packageManager.canRequestPackageInstalls()
                        if (!hasInstallPermission) {
                            startInstallPermissionSettingActivity()
                            return
                        }
                    }
                } else {
                    intent.setDataAndType(
                        Uri.fromFile(apkFile),
                        "application/vnd.android.package-archive"
                    )
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                if (mContext.packageManager.queryIntentActivities(intent, 0).size > 0) {
                    mContext.startActivity(intent)
                }
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
//        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + mActivity.getPackageName()));
//        mActivity.startActivityForResult(intent, 333);
        val intent = Intent()
        //获取当前apk包URI，并设置到intent中（这一步设置，可让“未知应用权限设置界面”只显示当前应用的设置项）
        val packageURI = Uri.parse("package:" + mActivity.getPackageName())
        intent.data = packageURI
        //设置不同版本跳转未知应用的动作
        if (Build.VERSION.SDK_INT >= 26) {
            //intent = new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
            intent.action = Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES
        } else {
            intent.action = Settings.ACTION_SECURITY_SETTINGS
        }
        //        mActivity.startActivityForResult(intent, 333);
        mActivity.startActivity(intent)
    }
}